import { Question } from '@/types/Course'
import { Exam } from '@/types/QuestionBankType'
import { defineStore } from 'pinia'




/**
 * 组卷数据存储
 */
export const usePaperStore = defineStore('paper', {
  state: () => ({
    currentPaper: null as Exam | null,
    userAnswers: {} as Record<number, Record<number, string>>, // { exerciseId: { questionId: answer } }
    parsedOptions: {} as Record<number, Record<number, Array<{ number: string; content: string }>>>
  }),
  actions: {
    // 设置试卷数据
    setPaperData(data: Exam) {
      console.log('调用了方法')
      this.currentPaper = data
      // 初始化答案存储结构
      
      data.exercises.forEach(exercise => {
        this.userAnswers[exercise.exercisesId] = {}
        this.parsedOptions[exercise.exercisesId] = {} // 初始化选项存储
        exercise.questions?.forEach(question => {
          this.userAnswers[exercise.exercisesId][question.recId] = ''

          // 解析 answerOptions
          try {
            const options = JSON.parse(question.answerOptions)?.data || []
            this.parsedOptions[exercise.exercisesId][question.recId] = options
          } catch (e) {
            console.error('解析选项失败:', e)
            this.parsedOptions[exercise.exercisesId][question.recId] = []
          }
        })
      })
      // 将数据存储到 localStorage
      localStorage.setItem('testpaperData', JSON.stringify(data));
    },

    // 获取解析后的选项
    getParsedOptions(exerciseId: number, questionId: number) {
      return this.parsedOptions[exerciseId]?.[questionId] || []
    },
    // 从 localStorage 恢复数据
    restoreData() {
      const data = localStorage.getItem('testpaperData');
      if (data) {
        const parsedData = JSON.parse(data)
        this.setPaperData(parsedData) // 重用setPaperData方法确保数据正确解析
      }
      console.log('取出来的数据'+data);
    },
    // 设置答案
    setUserAnswer(exerciseId: number, questionId: number, answer: string ) {
      if (!this.userAnswers[exerciseId]) {
        this.userAnswers[exerciseId] = {}
      }
      this.userAnswers[exerciseId][questionId] = answer
    },
    // 清空试卷数据
    clearPaperData() {
      this.currentPaper = null
      this.userAnswers = {}
    },
    // 计算总分
    calculateTotalScore(): number {
      if (!this.currentPaper) return 0
      return this.currentPaper.exercises.reduce((total, exercise) => {
        return total + exercise.questions?.reduce((exerciseTotal, question) => {
          const isCorrect = this.isAnswerCorrect(exercise.exercisesId, question.id, question.answer)
          return exerciseTotal + (isCorrect ? (question.score || 0) : 0)
        }, 0) || 0
      }, 0)
    },
    // 判断单个问题是否正确
    isAnswerCorrect(exerciseId: number, questionId: number, correctAnswer: string): boolean {
      return this.userAnswers[exerciseId]?.[questionId] === correctAnswer
    }
  }
})


// 在应用启动时调用 restoreData 恢复数据
const questionStore = usePaperStore();
questionStore.restoreData();